/*
 * Copyright (C) 2023 xuexiangjys(xuexiangjys@163.com)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

package com.xuexiang.templateproject.utils;

import android.graphics.Bitmap;
import android.util.Log;

import com.alibaba.sdk.android.oss.ClientConfiguration;
import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.OSS;
import com.alibaba.sdk.android.oss.OSSClient;
import com.alibaba.sdk.android.oss.ServiceException;
import com.alibaba.sdk.android.oss.callback.OSSCompletedCallback;
import com.alibaba.sdk.android.oss.callback.OSSProgressCallback;
import com.alibaba.sdk.android.oss.common.OSSLog;
import com.alibaba.sdk.android.oss.common.auth.OSSCredentialProvider;
import com.alibaba.sdk.android.oss.common.auth.OSSPlainTextAKSKCredentialProvider;
import com.alibaba.sdk.android.oss.common.auth.OSSStsTokenCredentialProvider;
import com.alibaba.sdk.android.oss.internal.OSSAsyncTask;
import com.alibaba.sdk.android.oss.model.GetObjectRequest;
import com.alibaba.sdk.android.oss.model.GetObjectResult;
import com.alibaba.sdk.android.oss.model.PutObjectRequest;
import com.alibaba.sdk.android.oss.model.PutObjectResult;
import com.xuexiang.templateproject.MyApp;
import com.xuexiang.xaop.annotation.DiskCache;
import com.xuexiang.xaop.annotation.IOThread;
import com.xuexiang.xutil.common.logger.Logger;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

public class OssUtils {

    public static final String accessKeyId = "LTAI5tBvpTrrZvqZ6cPmaMs6";
    public static final String accessKeySecret = "TFoXysgqyPqNNJplbfesHzWJpMo03N";
    public static final String securityToken = "ram::1387862572115694";
    public static final String URI = "https://lotai.oss-cn-hongkong.aliyuncs.com/";
    public static final String ossBucket = "lotai";
    public static final String endpoint = "http://oss-cn-hongkong.aliyuncs.com";
//    ClientConfiguration conf = new ClientConfiguration();
//        conf.setConnectionTimeout(15 * 1000); // connction time out default 15s
//        conf.setSocketTimeout(15 * 1000); // socket timeout，default 15s
//        conf.setMaxConcurrentRequest(5); // synchronous request number，default 5
//        conf.setMaxErrorRetry(2); // retry，default 2
    @DiskCache(enableEmpty = false)
    @IOThread
    public static   boolean uploadFile(String uploadFilePath,String objectKey) throws ServiceException, ClientException {

        OSSCredentialProvider credentialProvider = new OSSPlainTextAKSKCredentialProvider(OssUtils.accessKeyId, OssUtils.accessKeySecret);
        OSS oss = new OSSClient(MyApp.getContext(), OssUtils.endpoint, credentialProvider);
        PutObjectRequest put = new PutObjectRequest(OssUtils.ossBucket, objectKey, uploadFilePath);
        PutObjectResult putObjectResult =  oss.putObject(put);
        Logger.d("getETag"+putObjectResult.getETag());
        Logger.d("getStatusCode"+putObjectResult.getStatusCode()+"" );
        if(putObjectResult.getStatusCode() == 200)  return true;
        return false;
    }

    public static void  downloadFile(String objectKey){
        OSSCredentialProvider credentialProvider = new OSSPlainTextAKSKCredentialProvider(OssUtils.accessKeyId, OssUtils.accessKeySecret);
        OSS oss = new OSSClient(MyApp.getContext(), OssUtils.endpoint, credentialProvider);
        // Construct an object download request
        GetObjectRequest get = new GetObjectRequest(ossBucket, objectKey);

        OSSAsyncTask task = oss.asyncGetObject(get, new OSSCompletedCallback<GetObjectRequest, GetObjectResult>() {
            @Override
            public void onSuccess(GetObjectRequest request, GetObjectResult result) {
                // Request succeeds
//                Log.d("Content-Length", "" + getResult.getContentLength());

                InputStream inputStream = result.getObjectContent();

                byte[] buffer = new byte[2048];
                int len;

                try {
                    while ((len = inputStream.read(buffer)) != -1) {
                        // Process the downloaded data
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(GetObjectRequest request, ClientException clientExcepion, ServiceException serviceException) {
                // Request exception
                if (clientExcepion != null) {
                    // Local exception, such as a network exception
                    clientExcepion.printStackTrace();
                }
                if (serviceException != null) {
                    // Service exception
                    Log.e("ErrorCode", serviceException.getErrorCode());
                    Log.e("RequestId", serviceException.getRequestId());
                    Log.e("HostId", serviceException.getHostId());
                    Log.e("RawMessage", serviceException.getRawMessage());
                }
            }
        });

// task.cancel(); // Cancel the task

// task.waitUntilFinished(); // Wait till the task is finished as needed

    }


    @IOThread
    public static boolean upLoadBitmap(Bitmap bitmap, String objectKey) throws ServiceException, ClientException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        byte[] bytes = baos.toByteArray();
        OSSCredentialProvider credentialProvider = new OSSPlainTextAKSKCredentialProvider(OssUtils.accessKeyId, OssUtils.accessKeySecret);
        OSS oss = new OSSClient(MyApp.getContext(), OssUtils.endpoint, credentialProvider);
        PutObjectRequest put = new PutObjectRequest(OssUtils.ossBucket, objectKey, bytes);
//        put.setProgressCallback(new OSSProgressCallback<PutObjectRequest>() {
//            @Override
//            public void onProgress(PutObjectRequest request, long currentSize, long totalSize) {
//                Log.d("PutObject", "currentSize: " + currentSize + " totalSize: " + totalSize);
//            }
//        });
        PutObjectResult putObjectResult =  oss.putObject(put);
        Logger.d("getETag"+putObjectResult.getETag());
        Logger.d("getStatusCode"+putObjectResult.getStatusCode()+"" );
        if(putObjectResult.getStatusCode() == 200)  return true;
        return false;
    }

}
